using System.Collections.Generic;
using Android.Views;
using Android.Widget;
using AppRobot.Models;
using Android.Content;
using AndroidX.RecyclerView.Widget;

namespace AppRobot.Adapters
{
    class InfoAdapter : RecyclerView.Adapter
    {
        readonly Context _context;
        IList<TalkMessage> _items;

        public InfoAdapter(Context context, IList<TalkMessage> items)
        {
            _context = context;
            _items = items;
        }

        public override int ItemCount => _items.Count;

        public void Add(TalkMessage item)
        {
            _items.Add(item);
            NotifyItemInserted(_items.Count - 1);
        }

        public void Remove(int position)
        {
            _items.RemoveAt(position);
            NotifyItemRemoved(position);
        }

        public override int GetItemViewType(int position)
        {
            return (int)_items[position].Flag;
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            (holder as InfoViewHolder).Update(_items[position]);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var inflater = LayoutInflater.From(_context);
            View itemView;
            if (viewType == (int)TalkType.Send)
            {
                itemView = inflater.Inflate(Resource.Layout.right_cell, parent, false);
            }
            else
            {
                itemView = inflater.Inflate(Resource.Layout.left_cell, parent, false);
            }

            var vh = new InfoViewHolder(itemView);
            return vh;
        }
    }

    class InfoViewHolder : RecyclerView.ViewHolder
    {
        private readonly TextView _textView;

        public InfoViewHolder(View itemView) : base(itemView)
        {
            _textView = itemView.FindViewById<TextView>(Resource.Id.TextView);
        }

        public void Update(TalkMessage message)
        {
            _textView.Text = message.Content;
        }
    }
}